package com.heiye.blog.ai.advisor.impl;

import com.heiye.blog.ai.domain.mapper.ChatMessageMapper;
import com.heiye.blog.ai.model.vo.AiChatReqVO;
import com.heiye.blog.framework.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.transaction.support.TransactionTemplate;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * @author: heiye
 * @date: 2025/11/19 下午5:07
 * @version: v1.0.0
 * @description:
 */
@Slf4j
public class RolePromptBuilderAdvisor implements StreamAdvisor {

    private final Prompt prompt;

    public RolePromptBuilderAdvisor(Prompt prompt) {
        this.prompt = prompt;
    }

    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest, StreamAdvisorChain streamAdvisorChain) {
        log.info("## 角色提示词构建 Advisor...");

        // 创建系统提示词
        SystemMessage systemMessage = new SystemMessage(prompt.getContents());

        // 获取到经过记忆聊天的消息
        List<Message> messages = chatClientRequest.prompt().getInstructions();

        // 将系统提示词添加到消息列表的最前面
        messages.addFirst(systemMessage);

        // 构建一个新的 ChatClientRequest 请求对象
        ChatClientRequest processedChatClientRequest = chatClientRequest
                .mutate()
                .prompt(chatClientRequest.prompt().mutate().messages(messages).build())
                .build();

        log.info("## 角色提示词构建完成... :{}", JsonUtils.toJsonString(processedChatClientRequest));

        return streamAdvisorChain.nextStream(processedChatClientRequest);
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
